<?php
/**
 * @author spenceryg
 * @date 2023/4/21
 * @time 9:43 上午
 * @focus love & life
 */


namespace app\admin\controller\sys\business;


use app\admin\controller\sys\model\ConfigClass;
use app\admin\controller\sys\model\ConfigItem;
use think\facade\Cache;

class SpConfigBusiness
{
    public static function getConfig()
    {
        $config = config();
        $classes = ConfigClass::select();
        foreach ($classes as $class) {
            $class_name = $class['name'];
            if(!isset($config[$class_name])) {
                $config[$class_name] = [];
            }
            $class_config = &$config[$class_name];

            $items = ConfigItem::where('config_class_id', $class['id'])->select();
            foreach ($items as $item){
                $item_name_arr = explode('__', $item['name']);
                $item_config = &$class_config;
                $size = sizeof($item_name_arr);
                foreach ($item_name_arr as $key => $this_name){
                    if($key === $size - 1) {
                        $item_config[$this_name] = $item['value'];
                    }else{
                        if(!isset($item_config[$this_name])){
                            $item_config[$this_name] = [];
                        }
                        $item_config = &$item_config[$this_name];
                    }
                }
            }

        }
        return $config;
    }


    public static function setConfig()
    {
        $config = Cache::get('sp_config');
        $config = null;
        if(!$config) {
            $config = self::getConfig();
            Cache::set('sp_config', $config, 60);
        }
        config($config);
    }
}
